
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';

const app = express();
const port = 3001;

app.use(cors()); 
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 数据库连接
mongoose.connect('mongodb://localhost:27017/myBlogdb', {
  useNewUrlParser: true,
})
.then(() => console.log('MongoDB 连接成功'))
.catch(err => console.error('MongoDB 连接失败:', err));

// 建立模型
const Blog = new mongoose.model('Blog', new mongoose.Schema({
  id: { type: Number },
  title: { type: String },
  body: { type: String },
  categories: { type: Array },
}));

// 
app.get('/', async (req, res) => {
  res.send('index');
});

// 新增文章
app.post('/blog', async (req, res) => {
  const blog = await Blog.create(req.body);
  res.send(blog);
});

// 获取文章列表
app.get('/blog', async (req, res) => {
  const blogs = await Blog.find();
  res.send(blogs);
});

// 删除文章
app.delete('/blog/:id', async (req, res) => {
  await Blog.findOneAndDelete(req.params.id);
  res.send({ status: true });
});

// 文章详情
app.get('/blogs/:id', async (req, res) => {
  const blog = await Blog.findById(req.params.id);
  res.send(blog);
});

// 更新文章
app.put('/blog/:id', async (req, res) => {
 const blog= await Blog.findByIdAndUpdate(req.params.id,req.body);

  res.send(blog);
  console.log("更新后文档："+blog);
});



// 分页显示
app.get('/blog/page', async (req, res) => {
  try {
    // 解析并验证参数
    const currentPage = parseInt(req.query.currentPage) || 1;
    const pageSize = parseInt(req.query.pageSize) || 2;

    // 校验参数合法性
    if (currentPage < 1 || pageSize < 1 || isNaN(currentPage) || isNaN(pageSize)) {
      return res.status(400).json({ 
        error: '无效参数', 
        message: 'currentPage和pageSize必须为正整数' 
      });
    }

    // 计算总记录数和分页数据
    const total = await Blog.countDocuments({});
    const data = await Blog.find({})
      .skip((currentPage - 1) * pageSize)  // 避免负skip值
      .limit(pageSize)
      .sort({ _id: -1 });

    res.json({ data, total });
  } catch (err) {
    res.status(500).json({ error: 'Server error', message: err.message });
  }
});

app.listen(port,()=>{
    console.log(`http://localhost:${port}`)
})